<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/* ****************************************************************************
  NAIYUMIE KING WANG JJANG Front End Developer <naiyumie@gmail.com>
  FileType:CRLF, Encording:UTF-8, Tab&Space:4/4
  ------------------------------------------------------------------------
  입수금
**************************************************************************** */

class Money extends N_Controller {

	/***************************************************
	 * preprocess
	 *     constructor
	 *     function
	 *     declaration
	 ***************************************************/
	public function __construct(){
		parent::__construct();

		$this->nUriExtend = array(
			'listSeg' => 'layout',
			'txSeg' => 'processCudAjax',
			'ntxSeg' => 'processListAjax',
			'createSeg' => 'layout'
		);
		$this->nUri = array_merge($this->nUri, $this->nUriExtend);

		$this->load->model('MoneyM');
		$this->load->model('DepositMoneyM');
	}

	public function index() {
		$this->layout();
	}


	/***************************************************
	 * view control : Layouts
	 ***************************************************/
	public function layout(){
		# local variables
		$retVal = '';
		$mode = '';

		$this->tilesHeader();
		$mode = empty(trim($this->nurl->decrypt($this->input->get('mode'))))? 'list' : trim($this->nurl->decrypt($this->input->get('mode')));

		$g01 = $this->GlobalM->getMembersCharactersList();
		$i01 = $this->GlobalM->getMembersList();
		switch($mode){
			case 'retrieve' :
				$pk_uid = trim($this->nurl->decrypt($this->input->get('article')));
				$r01 = $this->MoneyM->r01(array('pk_uid'=>$pk_uid));
				$viewArray = array('mode'=>$mode, 'r'=>$r01, 'g01'=>$g01, 'subjection'=>'상세 - 조회 / 수정');
			break;
			case 'create' :
				$viewArray = array('mode'=>$mode, 'g01'=>$g01, 'subjection'=>'상세 - 새 레코드 추가');
			break;
			case 'list' :
				$viewArray = array('mode'=>$mode, 'g01'=>$g01);
			break;
			case 'hunting_end_calculate' :
				$g01 = $this->MoneyM->r04();
				$viewArray = array('mode'=>$mode, 'g01'=>$g01, 'i01'=>$i01, 'subjection'=>'상세 - 사냥끝 정산');
			break;
			default:break;
		}
		$this->load->view('vMoney', $viewArray);
		$this->tilesFooter();
	}


	/***************************************************
	 * ajax process : List
	 ***************************************************/
	public function processListAjax(){

		# local variables
		$retVal = '';
		$modelworks = array();
		$data = array();
		$r01 = array();
		$modelSetVariables = array();

		# 검색 GET
		$keyOfWhereKey = trim($this->nurl->encrypt('whereKey'));
		$whereKey = trim($this->nurl->decrypt($this->input->get($keyOfWhereKey)));
		$keyOfWhereVal = trim($this->nurl->encrypt('whereVal'));
		$whereVal = trim($this->gibberishaes->dec($this->input->get($keyOfWhereVal), $this->input->post('GAesKey')) );
		//nlog($a = sprintf('where >> keyOfWhereKey[%s] whereKey[%s] keyOfWhereVal[%s] whereVal[%s]', $keyOfWhereKey, $whereKey,$keyOfWhereVal, $whereVal ));

		# 검색에 따른 배열 작성
		$isWhere = array();
		$whereOpt = '';
		if(empty($whereKey) === FALSE && empty($whereVal) === FALSE){
			//nlog('where---');

			# 검색 옵션
			if($whereKey == 'fk_characters_uid'){
				$whereOpt = 'absolute';
			}
			$m01 = $this->MoneyM->o01();
			//nlog($m01);
			foreach($m01 as $key=>$val){
				//echo $val['text'];
				//echo mb_strlen($val['text']);
				//echo PHP_EOL;
				$splitedString = preg_split('//u', $val['text'], -1, PREG_SPLIT_NO_EMPTY);
				foreach($splitedString as $k=>$v){
					//echo $v . PHP_EOL;
					if(strpos($v, $whereVal) !== false){
						//echo "True".PHP_EOL;
						//if($whereVal = ){}
						$whereVal = $val['code'];
						if($val['isAbsolute'] == 'y'){
							$whereOpt = 'absolute';
						}
					}
				}
				if(strpos($val['text'], $whereVal ) !== false){
					$whereVal = $val['code'];
					if($val['isAbsolute'] == 'y'){
						$whereOpt = 'absolute';
					}
				}
			}
			$isWhere=array(
				'whereKey' => $whereKey,
				'whereVal' => $whereVal,
				'whereOpt' => $whereOpt
			);

		}
		//nlog($a = sprintf('where >> %s=%s %s=%s', $keyOfWhereKey, $whereKey,$keyOfWhereVal, $whereVal ));
		//nlog('a');

		//nlog('isWhere>>>>>>>>>>>>>>>>>>>>>>>'.print_r($isWhere, true));

		# pagenation
		if(empty($isWhere) === FALSE){
			$modelSetVariables['where'] = $isWhere;
			//nlog('where+++');
		}
		//	nlog('where+++' . print_r($modelSetVariables, true));

		//$totalCount = $this->MoneyM->r02(          $test  );
		$totalCount = $this->MoneyM->r02($modelSetVariables);

		$modelSetVariables['paginationCfg'] = array(
			'seg1Arg' => $this->nUri['seg1'],
			'seg2Arg' => $this->nUri['seg2'],
			'articles_count' => 10,
			'page_size'	=> 10,
			'totalCount' => $totalCount,
			'get' => 'p1'
		);
		$this->npagination->init($modelSetVariables['paginationCfg']);
		$modelSetVariables['paginationCfg']['paginationFirst'] = $this->npagination->paginationCfg['paginationFirst'];
		$modelSetVariables['paginationCfg']['paginationSecond'] = $this->npagination->paginationCfg['paginationSecond'];

		$r01 = $this->MoneyM->r01($modelSetVariables);
		//nlog('r01 >> ', print_r($r01, true));

		$pagination = $this->npagination->out();
		//nlog('r01'.print_r($r01, true));
		//nlog('pagination'.$pagination);
		//nlog('totalCount'.$totalCount);

		# list data
		//$dataln = '';
		$datalnArray = array();
		foreach ($r01 as $key => $val) {
			$datalnArray[$key] = array(
				'clickEvent' => $this->nmover->jsLink(array('seg1'=>$this->nUri['seg1'], 'seg2'=>$this->nUri['listSeg'], 'queryString'=>array( 'mode'=>'retrieve', 'article'=>$val['pk_uid'] ))),
				'childes' => array(
					array('textValue'=>$val['pk_uid']),
					array('textValue'=>$val['characters_name']),
					//array('textValue'=>$val['fk_characters_uid']),
					array('textValue'=>$val['fg_flow_kr']),
					array('textValue'=>$val['no_money']),
					array('textValue'=>$val['flowing']),
					array('textValue'=>$val['tx_description'])
				)
			);
		}

		# out put json
		$data['listdata'] = $datalnArray;
		$data['pagination'] = $pagination;
		$retVal = json_encode($data);
		exit($retVal);
	}


	/***************************************************
	 * ajax process : Cud
	 ***************************************************/
	public function processCudAjax(){
		# local variables
		$retVal = '';
		$mode = '';
		$modelworks = array();
		$data = array();
		$process = '';

		# decoding and set mode
		//$data['tmp___posts'] = $this->input->post();
		$this->validatedValues = $this->nvalidation->postAesDecodes();
		$mode = trim($this->nurl->decrypt($this->input->get('mode')));
		nlog($mode);

		# for debug
		$data['tmp___validatedValues'] = print_r($this->validatedValues, TRUE);
		$data['tmp___validatedValues2'] = json_encode($this->validatedValues);

		# Validation Phase
		if($mode == 'create' || $mode == 'update'){
			# 기본 밸리데이션
			if(!$this->nvalidation->basicValidation(array('mode'=>$mode,'validationValueArray'=>$this->validatedValues,'fg_tableName'=>'tbl_item_money_characters'))){
				//print('>>> basicValidation valError');
				$data['mode'] = $mode;
				$data['process'] = 'validation';
				$data['processPhase'] = 'basic';
				$data['resultMessage'] = 'fail';
				$data['vStatArray'] = json_encode($this->nvalidation->vStatFailedResultArray);
				$retVal = json_encode($data);
				exit($retVal);
			}

			# 확장 밸리데이션 룰
			$this->extendValidationRuleArray = array(
				'uq_member_id' => array('email'),
				'fg_terms_of_use' => array('important(y)'),
				'fg_privacy_policy' => array('important(y)'),
				'pw_member_pw' => array('equalto(___member_pw)')
			);

			# 확장 밸리데이션
			if(!$this->nvalidation->extendValidation(array('mode'=>$mode,'validationValueArray'=>$this->validatedValues, 'extendValidationRuleArray'=>$this->extendValidationRuleArray))){
				//print_r($this->validatedValues);
				//print('>>> extendValidation valError');
				$data['mode'] = $mode;
				$data['process'] = 'validation';
				$data['processPhase'] = 'extend';
				$data['resultMessage'] = 'fail';
				$data['vStatArray'] = json_encode($this->nvalidation->vStatFailedResultArray);
				$retVal = json_encode($data);
				exit($retVal);
			} else {
				# 트랜젝션 되지 않을 값을 삭제한다.
				unset($this->validatedValues['___member_pw']);
			}
		}

		#delete validation phase
		if($mode == 'delete'){
			//nlog(print_r($this->validatedValues, true));
			foreach($this->validatedValues as $key=>$val){
				if($key != 'pk_uid'){
					unset($this->validatedValues[$key]);
				}
			}
			if(!$this->nvalidation->basicValidation(array('mode'=>$mode,'validationValueArray'=>$this->validatedValues))){
				//print('>>> basicValidation valError');
				$data['mode'] = $mode;
				$data['process'] = 'validation';
				$data['processPhase'] = 'basic';
				$data['resultMessage'] = 'fail';
				$retVal = json_encode($data);
				exit($retVal);
			}
			//nlog(print_r($this->validatedValues, true));
		}

		# for debug
		$data['tmp___this->nvalidation->vStatFailedResultArray'] = count($this->nvalidation->vStatFailedResultArray);
		//nlog('delete validation in 1 '.$mode);

		# db Transaction Phase
		if(@$this->validatedValues['pk_uid'] == '' && $mode == 'create'){
			$process .= 'create';
			//$this->validatedValues['dt_joined'] = getNowDate();
			//$this->validatedValues['tm_joined'] = getNowTime();
			$modelworks = $this->MoneyM->c01($this->validatedValues);

		} else if($mode == 'update' || $mode == 'retrieve') {
			$process .= 'update';
			$modelworks = $this->MoneyM->u01($this->validatedValues);

		} else if(@$this->validatedValues['pk_uid'] != '' && $mode == 'delete'){
			//nlog('delete validation in '.$mode);
			$process .= 'delete';
			$modelworks = $this->MoneyM->d01($this->validatedValues);

		} else if($mode == 'hunting_end_calculate'){
			//nlog( 'validatedValues >>> ');
			//nlog( $this->validatedValues );
			$process .= 'hunting_end_calculate';
			//$this->validatedValues['fk_characters_uid']
			$characterCalculatedMoney = $this->MoneyM->r03($this->validatedValues);
			$membersDepositMoney = $this->DepositMoneyM->r03($this->validatedValues);
			//nlog($characterCalculatedMoney);
			//nlog($membersDepositMoney);
			$willUpdateMembersDepositMoney = $membersDepositMoney + $characterCalculatedMoney;
			//nlog($willUpdateMembersDepositMoney);
			$calculatedArray = array(
				'fk_members_uid' =>$this->validatedValues['fk_members_uid'],
				'no_money' => $willUpdateMembersDepositMoney,
				'dt_flowing' => getNowDate(),
				'tm_flowing' => getNowTime()
			);
			$isDeletedCharactersMoneyList = $this->MoneyM->d02($this->validatedValues);
			if($isDeletedCharactersMoneyList == TRUE){
				$modelworks =  $this->DepositMoneyM->u03($calculatedArray);
			}
		}

		# out put json
		$data['mode'] = $mode;
		$data['process'] = $process;
		$data['resultMessage'] = $modelworks ? 'succ' : 'fail';
		$retVal = json_encode($data);
		exit($retVal);
	}

}
/* End of file */